package com.hbgjq.security.config;

import com.hbgjq.security.filter.TokenFilter;
import com.hbgjq.security.handler.MySuccessHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author :Gjq
 * @date :2021/1/6
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //使用bean校验权限 指定web路径
        http.authorizeRequests(authorize ->{
            authorize.antMatchers("/test/test/**").access("@myWebSecurity.check(authentication,request)");
        });
        TokenAuthenticationProcessingFilter tokenAuthenticationProcessingFilter = new TokenAuthenticationProcessingFilter(authenticationManagerBean());
        tokenAuthenticationProcessingFilter.setAuthenticationSuccessHandler(new MySuccessHandler());
        //默认规则
        http.authorizeRequests()
                //放行/ 和 /home目录 不需要登录权限
                .antMatchers("/", "/home" ,"login1").permitAll()
                .anyRequest().authenticated()
                .and()
                //开启基于表单的登录
                .formLogin()
                //设置表单登录的地址 将登录转发到login页面
                .loginPage("/login")
                .permitAll()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                //开启登录的功能
                .logout()
                .permitAll()
        .and().csrf().disable().addFilterAfter(new TokenFilter(),UsernamePasswordAuthenticationFilter.class)
        .addFilterAt(tokenAuthenticationProcessingFilter,UsernamePasswordAuthenticationFilter.class);
    }


    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}